﻿using System;
using System.Collections.Generic;
using ProtoBuf.Message;
using Dict;
using Dict.DataModel;
using Dict.Blo;
using UnityEngine;
#if !NAKED
using supersdkUnity;
#endif

namespace UI
{
    public class UIPlayerData
    {
        public string deviceKey;

        public string version;
        public string createRoleTime;
        public int contribution;

        //公会属性加成
        public int needRefreshUnionProp;
        //工会成员等级(会长、副会长)
        public int unionMember;
        //工会红点计数器
        public int unionRedPoint;

        #region MainPlayerIcon
        public bool isPlayerMan = false;

        /// <summary>
        /// 主人物对应的卡牌唯一ID
        /// </summary>
        public string heroWarUID;
        /// <summary>
        /// 主人物英雄ID
        /// </summary>
        public string mainHeroId
        {
            get
            {
                return instPlayerData.GetBattleCamp(1).hero.heroId;
            }
        }
        /// <summary>
        /// 主人物ICON
        /// </summary>
        public string iconResName
        {
            get
            {
                return instPlayerData.GetBattleCamp(1).hero.heroData.iconName;
            }
        }
        #endregion

        #region Energy 精力
        public const float Energy_DURATION = 1800;//体力CD时间
        private Countdown energyCountdown;
        private int showother;
        public void SetLastEnergyTime(long lastTime, int current, int max)
        {
            energyCountdown = new Countdown(Energy_DURATION, lastTime, max, current);
            if (onEnergyChanged != null)
            {
                onEnergyChanged();
            }
        }
        /// <summary>
        /// 是否自动宣战
        /// </summary>
        public bool IsAutoWarOn
        {
            get 
            {
                return PlayerPrefs.GetInt("auto_war_on", 1) == 1 ? true : false;
            }
            set
            {
                PlayerPrefs.GetInt("auto_war_on", value ? 1 : 0);
            }
        }
        /// <summary>
        /// 是否显示其他玩家
        /// </summary>
        public bool IsShowPlayer
        {
            get {
                return PlayerPrefs.GetInt("show_other_player", 1) == 1 ? true : false;
            }
            set
            {
                PlayerPrefs.SetInt("show_other_player", value ? 1 : 0);
            }
        }

        /// <summary>
        /// 耐力
        /// </summary>
        public int Energy
        {
            get
            {
                if(energyCountdown == null)
                {
                    return 0;
                }
                return energyCountdown.Current;
            }
            set
            {
                energyCountdown.Current = value;
                if (onEnergyChanged != null)
                {
                    onEnergyChanged();
                }
            }
        }
        public int maxEnergy;
        public double GetEnergyRecoveryTimeLeft()
        {
            return energyCountdown.GetNextRecoveryTime();
        }
        public double GetEnergyAllRecoveryTimeLeft()
        {
            return energyCountdown.GetAllRecoveryTime();
        }

        OnValueChanged onEnergyChanged;
        public void AddOnEnergyChanged(OnValueChanged onChange)
        {
            onEnergyChanged += onChange;
        }
        public void RemoveOnEnergyChanged(OnValueChanged onChange)
        {
            onEnergyChanged -= onChange;
        }
        #endregion

        #region Stamina 体力
        public const float Stamina_DURATION = 360;
        private Countdown staminaCountdown;
        public void SetLastStaminaTime(long lastTime, int current, int max)
        {
            staminaCountdown = new Countdown(Stamina_DURATION, lastTime, max, current);
            if (onStaminaChange != null)
            {
                onStaminaChange();
            }
        }
        /// <summary>
        /// 体力
        /// </summary>
        public int Stamina
        {
            get
            {
                if (staminaCountdown == null)
                    return 0;
                return staminaCountdown.Current;
            }
            set
            {
                staminaCountdown.Current = value;
                if (onStaminaChange != null)
                {
                    onStaminaChange();
                }
            }
        }
        public int maxStamina;
        public double GetStaminaRecoveryTimeLeft()
        {
            return staminaCountdown.GetNextRecoveryTime();
        }
        public double GetStaminaAllRecoveryTimeLeft()
        {
            return staminaCountdown.GetAllRecoveryTime();
        }
        OnValueChanged onStaminaChange;
        public void AddOnStaminaChanged(OnValueChanged onChange)
        {
            onStaminaChange += onChange;
        }

        public void RemoveOnStaminaChange(OnValueChanged onChange)
        {
            onStaminaChange -= onChange;
        }
        #endregion
        /// <summary>
        /// 当前好友数量
        /// </summary>
        public int currentFriendNum = -1;
        #region 野外疲劳值
        private int tiredness;
        public int Tiredness
        {
            get
            {
                return tiredness;
            }
            set
            {
                tiredness = value;
                if (onTirednessChanged != null)
                {
                    onTirednessChanged();
                }
            }
        }

        OnValueChanged onTirednessChanged;
        public void AddOnTirednessChanged(OnValueChanged onChange)
        {
            onTirednessChanged += onChange;
        }
        public void RemoveOnTirednessChanged(OnValueChanged onChange)
        {
            onTirednessChanged -= onChange;
        }


        #endregion

        #region 出狱时间
        public long redeemTime;
        #endregion

        public string teamId;
        public Team team;

        public bool IsHaveSelectServerCache()
        {
            return !string.IsNullOrEmpty(serverUID);
        }

        public void SelectServer(ProtoBuf.Message.ConfigServerZone select) {
            this.currentZone = select;
            serverUID = select.globalServerKey;
            ZoneId = select.serverId;
        }

        public void ClearSelectServerCache() {
            serverUID = "";
        }

        public ProtoBuf.Message.ConfigServerZone currentZone = null;
        private const string ZONE_ID_KEY = "zoneKey";
        private const string ZONE_ID = "ZoneId";
        private int zoneId = -1;
        public int ZoneId
        {
            set 
            {
                PlayerPrefs.SetInt(ZONE_ID, value);
                zoneId = value;
            }
            get
            {
                if(zoneId == -1)
                {
                    zoneId = PlayerPrefs.GetInt(ZONE_ID, -1);
                }
                return zoneId;
            }
        }
        public long playerId;//主角唯一ID
        //private int zoneId = -1;//

        private string _serverUID = "";
        public string serverUID {
            get {
                if (string.IsNullOrEmpty(_serverUID))
                {
                    _serverUID = PlayerPrefs.GetString(ZONE_ID_KEY, "");
                }
                return _serverUID;
            }
            private set {
                _serverUID = value;
                PlayerPrefs.SetString(ZONE_ID_KEY, value);
            }
        }

        public string name;
        #region Level
        private int _level;
        public int level
        {
            get
            {
                return _level;
            }
            set
            {
                if(_level != value)
                {
                    var hero = instPlayerData.GetUIHero(heroWarUID);
                    if(hero != null)
                    {
                        hero.ResetAttribute();
                    }
                }
                _level = value;
            }
        }
        public long exp;
        public long maxExp;
        public bool isLevelMax
        {
            get { return level >= maxLevel; }
        }
        public int maxLevel
        {
            get
            {
                return Dict.DictDataManager.Instance.tableLevelLimitDao.CacheList[Dict.DictDataManager.Instance.tableLevelLimitDao.CacheList.Count - 1].playerLev;
            }
        }

        //public void AddExp(long addExp)
        //{
        //    bool isLevelUp = false;
        //    int preLevel = level;
        //    exp += addExp;
        //    while (exp >= maxExp && !isLevelMax)
        //    {
        //        exp -= addExp;
        //        var perDu = Dict.Blo.DictPlayerBlo.GetUserExpInfoByLevel(level);
        //        if (perDu != null)
        //        {
        //            Stamina += perDu.stamina;
        //            Energy += perDu.energy;
        //        }
        //        level++;
        //        //isLevelUp = true;
        //        var du = Dict.Blo.DictPlayerBlo.GetUserExpInfoByLevel(level);
        //        if (du != null)
        //        {
        //            maxExp = du.exp;
        //        }
        //        else
        //        {
        //            maxExp = 0;
        //        }
        //    }

        //    if (isLevelUp)
        //    {
        //        StaticData.hasLevelUp = true;
        //    }
        //}

        public int vip;
        public int chargeConut;//充值次数
        public int warriorBagSize;
        public int equipBagSize;
        public int petBagSize;

        public bool IsHeroFull()
        {
            return warriorBagSize <= instPlayerData.InstHeros.Count;
        }

        public bool IsEquipFull()
        {
            return equipBagSize <= instPlayerData.GetEquipTreasureTotalCount();
        }

        public bool IsPetFull()
        {
            return petBagSize <= instPlayerData.InstPets.Count;
        }
        /// <summary>
        /// 悬赏积分（战功）
        /// </summary>
        public int bossScore;
        /// <summary>
        /// 攻略点数（威名）
        /// </summary>
        public int strategyScore;
        /// <summary>
        /// 滞留之光 
        /// </summary>
        public int retentionLight;  //
        public long chargeDiamond;//已经充值了xx钻石
        public long monthCardEndTime;//月卡到期时间
        public int permentType;//是否购买终身月卡；1说明购买了终身月卡
        public int wantedLeftAttTimes; //悬赏任务剩余攻击次数
        public long wantedLastAddTime; //悬赏任务上次恢复次数时刻
        public int cookingLevel;    //料理等级
        public int cookingExp;      //料理经验
        public int smeltLevel;    //锻造等级
        public int smeltExp;      //锻造经验
        public Dictionary<string, string> lifeSkills;   //生活技能，（料理技能，冶炼技能等等）
        public string curTitle;
        public List<string> ownTitleList;

        public void UpdateLifeSkills(List<string> list)
        {
            if (lifeSkills == null)
                lifeSkills = new Dictionary<string, string>();
            lifeSkills.Clear();
            foreach(var i in list)
            {
                lifeSkills[i] = i;
            }
        }

        public void AddPlayerTitle(TitleInfo title)
        {
            //Debug.Log("<color=green>-----------------"+ title.titleId +"------------------</color>");
            foreach (string own in ownTitleList)
            {
                if (own.Equals(title.titleId) && title.state == 1)
                {
                    return;
                }
            }
            ownTitleList.Add(title.titleId);
        }

        public void UpdatePlayerTitle(string title, List<TitleInfo> list)
        {
            curTitle = title;

            if (ownTitleList == null)
                ownTitleList = new List<string>();
            ownTitleList.Clear();
            foreach (var i in list)
            {
                if(i.state == 1)
                    ownTitleList.Add(i.titleId);
            }
        }

        public int maxEquipLevel
        {
            get
            {
                return Dict.DictDataManager.Instance.tableLevelLimitDao.GetById(this.level).equipMaxLev;
            }
        }
        public int maxTreaLevel
        {
            get
            {
                return Dict.DictDataManager.Instance.tableLevelLimitDao.GetById(this.level).treaMaxLev;
            }
        }

        public int maxPetLevel
        {
            get
            {
                //return Dict.DictDataManager.Instance.tablePetTalen.GetById(this.level).treaMaxLev;
                return 0;
            }

        }

        /// <summary>
        /// 添加经验
        /// </summary>
        public void AddUserExp(int exp)
        {
            //AddExp(exp);
        }
        #endregion
        #region Coin
        public long coin;
        public void AddCoin(long addNum)
        {
            coin += addNum;
        }
        public void SubCoin(long subNum)
        {
            coin -= subNum;
        }
        #endregion

        #region Diamond
        public long diamond;
        public void AddDiamond(long addNum)
        {
            diamond += addNum;
        }
        public void SubDiamond(long subNum)
        {
            diamond -= subNum;
        }

        #endregion

        #region Prestige
        public long prestige;// 声望
        public void AddPrestige(long addNum)
        {
            prestige += addNum;
        }
        public void SubPrestige(long subNum)
        {
            prestige -= subNum;
        }
        #endregion
        
        #region 首充标志位
        public bool showFirstRecharge = false;
        #endregion

        public void Clear()
        {
            if (simpleGoods != null)
            {
                simpleGoods.Clear();
            }
            simpleGoods = null;

            if (fragEquipments != null)
            {
                fragEquipments.Clear();
            }
            fragEquipments = null;

            if (fragPets != null){
                fragPets.Clear();
            }
            fragPets = null;

            if (fragHeros != null)
            {
                fragHeros.Clear();
            }
            fragHeros = null;

            if (itemShopProductList != null)
            {
                itemShopProductList.Clear();
            }
            itemShopProductList = null;

            if (instPlayerData != null)
            {
                instPlayerData.Clear();
            }
            instPlayerData = null;

            if(fishItems != null)
            {
                fishItems.Clear();
            }
            fishItems = null;
            
            if (mineItems != null)
            {
                mineItems.Clear();
            }
            mineItems = null;
        }

        private UIInstPlayerData instPlayerData;
        public UIInstPlayerData InstPlayerData
        {
            get
            {
                return instPlayerData;
            }
        }

        /// <summary>
        /// dict_key,data
        /// </summary>
        /// 
        private Dictionary<string, UISimpleItem> simpleGoods;//所有道具
        private Dictionary<string, UIFragItem> fragEquipments;//所有装备碎片
        private Dictionary<string, UIFragItem> fragPets; //宠物碎片
        public UITreasureFrag treasureFrag = new UITreasureFrag();
        public UIWorldSeed worldSeed = new UIWorldSeed();
        private Dictionary<string, UIFragItem> fragHeros;//所有武者碎片
        private Dictionary<string, UIFishItem> fishItems;//所有料理等
        private Dictionary<string, UIMineItem> mineItems;//所有矿石
        private Dictionary<string, UIShopProduct> itemShopProductList;
        public Dictionary<int, string> setHpItems; //野外回血快捷键
        public DateTime avoidPlunderTime = System.DateTime.UtcNow;

       
        private int currentWorldSeedLevel=-1;
        public int CurrentWorldSeedLevel
        {
            get
            {
                return currentWorldSeedLevel;
            }
            set
            {
                currentWorldSeedLevel = value;
                worldSeed.SetLevel(currentWorldSeedLevel);
                instPlayerData.ResetAllFormationAttribute();

            }
        }

        public string currentGuideId = null;


        //private int 


        public void ResetAvoidPlunderTime(long surplusTime)
        {
            avoidPlunderTime = ServerTimerTool.CurrentUTCTime.AddMilliseconds(surplusTime);
        }

        public long GetAvoidPlunderSurplusTime()
        {
            return avoidPlunderTime.Ticks - ServerTimerTool.CurrentUTCTime.Ticks;
        }

        #region 初始化
        //private bool inited = false;

        public void RefreshData(SCPlayer playerData)
        {
            ResetPlayer(playerData.player);
        }

        public void InitData(ProtoBuf.Message.SCPlayerLogin player,ProtoBuf.Message.SCEquipmentTreasureList equipList, ProtoBuf.Message.SCWarriorList warriorList, ProtoBuf.Message.SCItemList itemList, ProtoBuf.Message.SCFragmentList frageMentList, ProtoBuf.Message.SCFormationList formationList,ProtoBuf.Message.SCChangeNameTimes changeNameTimes,ProtoBuf.Message.SCGemAndCookingList gemAndCookList,SCPetList petList)
        {
            //inited = false;
            //DataMessageTool.AddHandler(DataMessage.INST_DATA_ATTRIBUTE_UPDATE, OnInstDataUpdate);


            instPlayerData = new UIInstPlayerData();
            instPlayerData.InitData(equipList.equipmentList, equipList.treasureList, warriorList.warriorList, formationList.formationList, formationList.helperList,petList.petList);
            this.heroWarUID = player.player.heroWarId;
            this.needRefreshUnionProp = player.player.needRefreshUnionProp;
            
            ResetPlayer(player.player);
            InitItemData();

            AddSimpleItem(itemList.itemList);
            //UnityEngine.Debug.Log("playerData.itemList:" + itemList.itemList.Count);
            AddSimpleItem(frageMentList.fragEquipmentList);
            //UnityEngine.Debug.Log("playerData.fragEquipmentList:" + frageMentList.fragEquipmentList.Count);
            AddSimpleItem(frageMentList.fragTreasureList);
            //UnityEngine.Debug.Log("playerData.fragTreasureList:" + frageMentList.fragTreasureList.Count);
            AddSimpleItem(frageMentList.fragWarriorList);
            AddSimpleItem(frageMentList.fragPetList);
            //UnityEngine.Debug.Log("playerData.fragHeroList:" + frageMentList.fragWarriorList.Count);
            //inited = true;
            AddSimpleItem(gemAndCookList.cookingList);
            AddSimpleItem(gemAndCookList.gemList);

            InitItemShopData();

            lifeSkills = new Dictionary<string, string>();
            ownTitleList = new List<string>();
            setFieldHpItems(gemAndCookList.shortCut1, gemAndCookList.shortCut2);

        }

        public void ResetPlayer(ProtoBuf.Message.Player data)
        {
            if(instPlayerData == null)
            {
                Debug.LogError("inst player data not init ");
                return;
            }
            playerId = data.playerId;
            name = data.name;

            if (level < data.level && level != 0)
            {
                level = data.level;
				#if !NAKED
                if (GameConfig.Instance.platform == 2 && SuperSDKUnity3D.isSupported(SuperSDKDataKeys.Function.SUBMIT_DATA))
                {
                    Debug.Log("level up");

                    PlatformSDK.GetInstance().LevelUpSubmit();
                }
				#endif
            }
            else
            {
                level = data.level;
            }
            if (!isLevelMax)
            {
                exp = data.exp;
                var du = Dict.Blo.DictPlayerBlo.GetUserExpInfoByLevel(level);
                if (du != null)
                {
                    maxExp = du.exp;
                }
            }
            else
            {
                exp = 1;
                maxExp = 1;
            }
            coin = data.coin;
            diamond = data.diamond;
            vip = data.vip;

            
            chargeConut = data.chargeCount;
            chargeDiamond = data.chargeDiamond;
            contribution = data.contribution;
            monthCardEndTime = data.monthCardEndTime;
            permentType = data.permanentCardValid;
            warriorBagSize = data.warriorBagSize;
            equipBagSize = data.equipBagSize;
            petBagSize = data.petBagSize;
            retentionLight = data.light;
            prestige = data.popularity;
            bossScore = data.score;
            wantedLeftAttTimes = data.wantedAttTimes;
            wantedLastAddTime = data.wantedAttTime;
            strategyScore = data.point;
            needRefreshUnionProp = data.needRefreshUnionProp;
            

            CurrentWorldSeedLevel = data.currentWorldSeedId;
            //worldSeed.SetLevel(currentWorldSeedLevel);

            currentGuideId = DictDataManager.Instance.tableGuideDao.GetByOneIndex(data.noviceGuideSchedule)[0].guideId;

            this.heroWarUID = data.heroWarId;
            //var mainHero = GetUIHero(heroWarUID);
            maxEnergy = 30;        // TEMP
            maxStamina = 100;       // TEMP
            SetLastEnergyTime(data.energyLastRefreshTime, data.energy, this.maxEnergy);
            SetLastStaminaTime(data.staminaLastRefreshTime, data.stamina, this.maxStamina);

            redeemTime = data.redeemTime;

            //redeemTime = ServerTimerTool.CurrentJavaTime() + 20000;
            if (redeemTime>ServerTimerTool.CurrentUTCJavaTime())
            {
                StaticData.isPlayerNeedJail = true;
            }
            else
            {
                StaticData.isPlayerNeedJail = false;
            }

            //
            StaticData.UnionAttribute();
        }

        private void InitItemData()
        {
            simpleGoods = new Dictionary<string, UISimpleItem>();
            fragEquipments = new Dictionary<string, UIFragItem>();
            fragPets = new Dictionary<string, UIFragItem>();
            treasureFrag.Clear();
            fragHeros = new Dictionary<string, UIFragItem>();
            fishItems = new Dictionary<string, UIFishItem>();
            mineItems = new Dictionary<string, UIMineItem>();

            foreach (var data in DictDataManager.Instance.tableItemDao.CacheList)
            {
                simpleGoods[data.itemId] = new UISimpleItem(data);
            }

            foreach (var data in DictDataManager.Instance.tableFishSkillDao.CacheList)
            {
                fishItems[data.FishItemID] = new UIFishItem(data);
            }

            foreach (var data in DictDataManager.Instance.tableMineSkillDao.CacheList)
            {
                mineItems[data.MineItemID] = new UIMineItem(data);
            }

            foreach (var data in DictDataManager.Instance.tableFragDao.CacheList)
            {
                if (data.id.StartsWith(Dict.Config.TableConst.frag_equip))
                {
                    fragEquipments[data.id] = new UIFragItem(data);
                }
                //else if (data.id.StartsWith(Dict.Config.TableConst.frag_trea))
                //{
                //    //fragTreasures[data.id] = new UIFragItem(data);
                //}
                else if (data.id.StartsWith(Dict.Config.TableConst.frag_war))
                {
                    fragHeros[data.id] = new UIFragItem(data);
                }
                else if(data.id.StartsWith(Dict.Config.TableConst.frag_pet))
                {
                    fragPets[data.id] = new UIFragItem(data);
                }
                else
                {
                    //还有很多其他东西,接着写
                }
            }
        }

        private void InitItemShopData()
        {
            itemShopProductList = new Dictionary<string, UIShopProduct>();
        }

        #endregion

        #region 查
        /// <summary>
        /// 获取装备
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<UIEquipment> GetUIEquipments(string id)
        {
            //todo
            return null;
        }
        public UIEquipment GetUIEquipment(string guid)
        {
            return instPlayerData.GetUIEquipment(guid);
        }

        public bool HasItem(string id)
        {
            return simpleGoods.ContainsKey(id);
        }
        /// <summary>
        /// 获取宝物
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<UITreasure> GetUITreasures(string id)
        {
            return null;//todo
        }
        public UITreasure GetUITreasure(string guid)
        {
            return instPlayerData.GetUITreasure(guid);
        }
        /// <summary>
        /// 获取武者
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<UIHero> GetUIHeros(string id)
        {
            return null;//todo
        }
        public UIHero GetUIHero(string guid)
        {
            return instPlayerData.GetUIHero(guid);
        }

        /// <summary>
        /// 获取宠物
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public List<UIPet> GetUIPets(string id)
        {
            //todo
            return null;
        }
        public UIPet GetUIPet(string guid)
        {
            return instPlayerData.GetUIPet(guid);
        }
        public UIHeroFormation GetBattleCamp(int pos)
        {
            return instPlayerData.GetBattleCamp(pos);
        }
        /// <summary>
        /// 获取道具
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public UISimpleItem GetSimpleGoods(string id)
        {
            return simpleGoods[id];
        }
        public UISimpleItem GetCopySimpleGoods(string id)
        {
            return simpleGoods[id].Clone();
        }

        public long GetSimpleItemCount(string id)
        {
            if (simpleGoods.ContainsKey(id))
            {
                return simpleGoods[id].num;
            }
            else
            {
                return 0;
            }
        }

        public bool IsHaveCanCook()
        {
            List<TableFishSkill> list = DictFishBlo.GetFishSkillList("dish");
            foreach (var t in list)
            {
                var fishItem = GetFishItem(t.FishItemID);
                if (fishItem.GetCanMakeNum() > 0 && StaticData.playerData.cookingLevel >= fishItem.fishData.LevelLimit)
                {
                    return true;
                }
            }
            return false;
        }

        public UIFishItem GetFishItem(string id)
        {
            return fishItems[id];
        }

        public long GetFishItemCount(string id)
        {
            if (fishItems.ContainsKey(id))
            {
                return fishItems[id].num;
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// 是否有可以提炼的矿石or可制作的宝石
        /// </summary>
        /// <returns></returns>
        public bool IsHaveMineCanResolve()
        {
            foreach (var item in mineItems)
            {
                if (item.Value.mineData.Type == MineItemType.STONE)
                {
                    if (item.Value.num >= 5 && StaticData.playerData.smeltLevel >= item.Value.mineData.LevelLimit)
                    {
                        return true;
                    }
                }
                else if (item.Value.mineData.Type == MineItemType.MAGICGEM)
                {
                    if (item.Value.GetCanMakeNum() > 0 && StaticData.playerData.smeltLevel >= item.Value.mineData.LevelLimit)
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        public UIMineItem GetMineItem(string id)
        {
            if(mineItems.ContainsKey(id))
                return mineItems[id];
            return null;
        }

        public long GetMineItemCount(string id)
        {
            if (mineItems.ContainsKey(id))
            {
                return mineItems[id].num;
            }
            else
            {
                return 0;
            }
        }

        public UIShopProduct GetItemShopProduct(string productId)
        {
            return itemShopProductList[productId];
        }

        public Dictionary<string, UIShopProduct> ItemShopProductList
        {
            get
            {
                return itemShopProductList;
            }
        }

        public Dictionary<string, UISimpleItem> SimpleGoods
        {
            get
            {
                return simpleGoods;
            }
        }
        public Dictionary<string, UIFragItem> FragEquipments
        {
            get
            {
                return fragEquipments;
            }
        }


        public Dictionary<string, UIFragItem> FragHeros
        {
            get
            {
                return fragHeros;
            }
        }

        public Dictionary<string,UIFragItem> FragPets
        {
            get
            {
                return fragPets;
            }
        }
        public Dictionary<string, UIFishItem> FishItems
        {
            get
            {
                return fishItems;
            }
        }

        /// <summary>
        /// 不包括金币和钻石
        /// </summary>
        /// <returns></returns>
        public List<UISimpleItem> GetSimpleGoodsOrderByStar()
        {
            List<UISimpleItem> list = new List<UISimpleItem>();
            foreach (var item in simpleGoods)
            {
                if (item.Value.num > 0 && item.Value.itemData.itemId != "item_200" && item.Value.itemData.itemId != "item_201")
                {
                    list.Add(item.Value);
                }
            }

            list.Sort(delegate (UISimpleItem a, UISimpleItem b)
            {
                if (a.itemData.star > b.itemData.star)
                {
                    return -1;
                }
                else if (a.itemData.star < b.itemData.star)
                {
                    return 1;
                }

                return 0;
            });

            return list;
        }

        public List<UIFishItem> GetFishItemsOrderByStar()
        {
            List<UIFishItem> list = new List<UIFishItem>();
            foreach(var item in fishItems)
            {
                if (item.Value.num > 0)
                    list.Add(item.Value);
            }

            list.Sort(delegate (UIFishItem a, UIFishItem b)
            {
                if (a.fishData.Quality > b.fishData.Quality)
                {
                    return -1;
                }
                else if (a.fishData.Quality < b.fishData.Quality)
                {
                    return 1;
                }

                return 0;
            });

            return list;
        }

        public List<UIFishItem> GetDishItemsOrderByStar()
        {
            List<UIFishItem> list = new List<UIFishItem>();
            foreach (var item in fishItems)
            {
                if (item.Value.num > 0 && item.Value.fishData.Type == FishItemType.DISH)
                    list.Add(item.Value);
            }

            list.Sort(delegate (UIFishItem a, UIFishItem b)
            {
                if (a.fishData.Quality > b.fishData.Quality)
                {
                    return -1;
                }
                else if (a.fishData.Quality < b.fishData.Quality)
                {
                    return 1;
                }

                return 0;
            });

            return list;
        }

        public List<UIMineItem> GetMineItemsOrderByStar()
        {
            List<UIMineItem> list = new List<UIMineItem>();
            foreach (var item in mineItems)
            {
                if (item.Value.num > 0)
                    list.Add(item.Value);
            }

            list.Sort(delegate (UIMineItem a, UIMineItem b)
            {
                if (a.mineData.Quality > b.mineData.Quality)
                {
                    return -1;
                }
                else if (a.mineData.Quality < b.mineData.Quality)
                {
                    return 1;
                }

                if (a.mineData.Level > b.mineData.Level)
                {
                    return -1;
                }
                else if (a.mineData.Level < b.mineData.Level)
                {
                    return 1;
                }

                return 0;
            });

            return list;
        }

        public List<UIMineItem> GetMineItemsForCompose()
        {
            List<UIMineItem> list = new List<UIMineItem>();
            foreach (var item in mineItems)
            {
                if (item.Value.num > 0 && item.Value.mineData.Type == MineItemType.MAGICGEM) // && item.Value.mineData.composeMeterial == 1)
                    list.Add(item.Value);
            }

            list.Sort(delegate (UIMineItem a, UIMineItem b)
            {
                if (a.mineData.Level < b.mineData.Level)
                {
                    return -1;
                }
                else if (a.mineData.Level > b.mineData.Level)
                {
                    return 1;
                }

                if (a.mineData.Color < b.mineData.Color)
                {
                    return -1;
                }
                else if (a.mineData.Color > b.mineData.Color)
                {
                    return 1;
                }

                return 0;
            });

            return list;
        }

        public List<UIMineItem> GetMineItemsForArray()
        {
            List<UIMineItem> list = new List<UIMineItem>();
            foreach (var item in mineItems)
            {
                if (item.Value.num > 0 && item.Value.mineData.Type == MineItemType.MAGICGEM) // && item.Value.mineData.composeMeterial == 1)
                    list.Add(item.Value);
            }

            list.Sort(delegate (UIMineItem a, UIMineItem b)
            {
                if (a.mineData.Level < b.mineData.Level)
                {
                    return 1;
                }
                else if (a.mineData.Level > b.mineData.Level)
                {
                    return -1;
                }

                if (a.mineData.Color < b.mineData.Color)
                {
                    return -1;
                }
                else if (a.mineData.Color > b.mineData.Color)
                {
                    return 1;
                }

                return 0;
            });

            return list;
        }


        /// <summary>
        /// 角色碎片背包排序
        /// </summary>
        /// <returns></returns>
        public List<UIFragItem> GetFragHerosForBagInOrder()
        {
            List<UIFragItem> list = new List<UIFragItem>();
            foreach (var item in fragHeros)
            {
                if (item.Value.num > 0)
                    list.Add(item.Value);
            }

            list.Sort(delegate (UIFragItem a, UIFragItem b)
            {
                TableHero aData = DictHeroBlo.GetTableHero(a.fragData.target);
                TableHero bData = DictHeroBlo.GetTableHero(b.fragData.target);
                //可合成的优先
                if (a.num >= a.fragData.num)
                {
                    if (b.num < b.fragData.num)
                    {
                        return -1;
                    }
                }
                else
                {
                    if (b.num >= b.fragData.num)
                    {
                        return 1;
                    }
                }

                //品质优先
                if (aData.quality > bData.quality)
                {
                    return -1;
                }
                else if (aData.quality < bData.quality)
                {
                    return 1;
                }
                else
                {
                    if (a.num > b.num)
                        return -1;
                    else if (a.num < b.num)
                        return 1;
                }
                return 0;
            });

            return list;
        }

        /// <summary>
        /// 角色碎片出售排序
        /// </summary>
        /// <returns></returns>
        public List<UIFragItem> GetFragHerosForSellInOrder()
        {
            List<UIFragItem> list = new List<UIFragItem>();
            foreach (var item in fragHeros)
            {
                if (item.Value.num > 0)
                    list.Add(item.Value);
            }

            list.Sort(delegate (UIFragItem a, UIFragItem b)
            {
                TableHero aData = DictHeroBlo.GetTableHero(a.fragData.target);
                TableHero bData = DictHeroBlo.GetTableHero(b.fragData.target);

                //品质低优先
                if (aData.quality > bData.quality)
                {
                    return 1;
                }
                else if (aData.quality < bData.quality)
                {
                    return -1;
                }
                else
                {
                    if (a.num > b.num)
                        return 1;
                    else if (a.num < b.num)
                        return -1;
                }

                return 0;
            });

            return list;
        }

        /// <summary>
        /// 装备碎片背包排序
        /// </summary>
        /// <returns></returns>
        public List<UIFragItem> GetEquipFragListForBagInOrder()
        {
            List<UIFragItem> list = new List<UIFragItem>();
            foreach (var item in fragEquipments)
            {
                if (item.Value.num > 0)
                    list.Add(item.Value);
            }

            list.Sort(delegate (UIFragItem a, UIFragItem b)
            {
                TableEquip aData = DictEquipBlo.GetTableEquip(a.fragData.target);
                TableEquip bData = DictEquipBlo.GetTableEquip(b.fragData.target);
                //可合成的优先
                if (a.num >= a.fragData.num)
                {
                    if (b.num < b.fragData.num)
                    {
                        return -1;
                    }
                }
                else
                {
                    if (b.num >= b.fragData.num)
                    {
                        return 1;
                    }
                }

                //品质优先
                if (aData.quality > bData.quality)
                {
                    return -1;
                }
                else if (aData.quality < bData.quality)
                {
                    return 1;
                }
                else
                {
                    if (a.num > b.num)
                        return -1;
                    else if (a.num < b.num)
                        return 1;
                }
                return 0;
            });

            return list;
        }

        /// <summary>
        /// 装备碎片出售排序
        /// </summary>
        /// <returns></returns>
        public List<UIFragItem> GetEquipFragListForSellInOrder()
        {
            List<UIFragItem> list = new List<UIFragItem>();
            foreach (var item in fragEquipments)
            {
                if (item.Value.num > 0)
                    list.Add(item.Value);
            }

            list.Sort(delegate (UIFragItem a, UIFragItem b)
            {
                TableEquip aData = DictEquipBlo.GetTableEquip(a.fragData.target);
                TableEquip bData = DictEquipBlo.GetTableEquip(b.fragData.target);

                //品质低优先
                if (aData.quality > bData.quality)
                {
                    return 1;
                }
                else if (aData.quality < bData.quality)
                {
                    return -1;
                }
                else
                {
                    if (a.num > b.num)
                        return 1;
                    else if (a.num < b.num)
                        return -1;
                }
                return 0;
            });

            return list;
        }

        /// <summary>
        /// 宠物碎片背包排序
        /// </summary>
        /// <returns></returns>
        public List<UIFragItem> GetFragPetsForBagInOrder()
        {
            List<UIFragItem> list = new List<UIFragItem>();
            foreach (var item in fragPets)
            {
                if (item.Value.num > 0)
                    list.Add(item.Value);
            }

            list.Sort(delegate (UIFragItem a, UIFragItem b)
            {
                TablePet aData = DictPetBlo.GetTablePet(a.fragData.target);
                TablePet bData = DictPetBlo.GetTablePet(b.fragData.target);
                //可合成的优先
                if (a.num >= a.fragData.num)
                {
                    if (b.num < b.fragData.num)
                    {
                        return -1;
                    }
                }
                else
                {
                    if (b.num >= b.fragData.num)
                    {
                        return 1;
                    }
                }

                //品质优先
                if (aData.quality > bData.quality)
                {
                    return -1;
                }
                else if (aData.quality < bData.quality)
                {
                    return 1;
                }
                else
                {
                    if (a.num > b.num)
                        return -1;
                    else if (a.num < b.num)
                        return 1;
                }
                return 0;
            });

            return list;
        }

        /// <summary>
        /// 宠物碎片出售排序
        /// </summary>
        /// <returns></returns>
        public List<UIFragItem> GetFragPetsForSellInOrder()
        {
            List<UIFragItem> list = new List<UIFragItem>();
            foreach (var item in fragPets)
            {
                if (item.Value.num > 0)
                    list.Add(item.Value);
            }

            list.Sort(delegate (UIFragItem a, UIFragItem b)
            {
                TablePet aData = DictPetBlo.GetTablePet(a.fragData.target);
                TablePet bData = DictPetBlo.GetTablePet(b.fragData.target);

                //品质低优先
                if (aData.quality > bData.quality)
                {
                    return 1;
                }
                else if (aData.quality < bData.quality)
                {
                    return -1;
                }
                else
                {
                    if (a.num > b.num)
                        return 1;
                    else if (a.num < b.num)
                        return -1;
                }

                return 0;
            });

            return list;
        }

        /// <summary>
        /// 获取装备碎片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public UIFragItem GetFragEquipments(string id)
        {
            return fragEquipments[id];
        }
        /// <summary>
        /// 获取宝物碎片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        //public UIFragItem GetFragTreasures(string id)
        //{
        //    return fragTreasures[id];
        //}
        /// <summary>
        /// 获取武者碎片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public UIFragItem GetFragHeros(string id)
        {
            return fragHeros[id];
        }
        /// <summary>
        /// 获取宠物碎片
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public UIFragItem GetFragPets(string id)
        {
            return fragPets[id];
        }

        #endregion
        #region 增

        public void AddResultObj(ResultObject ro)
        {
            if (ro != null)
            {
                AddSimpleItem(ro.simps);
                AddEquipment(ro.equips);
                AddTreasure(ro.treas);
                AddHero(ro.wars);
                AddPet(ro.pets);
            }
            else
            {
                Debug.LogError("[ERROR] ResultObject is null !!!!!!!!!!!!!!");
            }
        }

        public void AddSimpleItem(List<SimpleItem> simpleItems)
        {
            foreach (var data in simpleItems)
            {
                if (data.id.StartsWith(Dict.Config.TableConst.item))
                {
                    simpleGoods[data.id].num += data.num;
                }
                else if (data.id.StartsWith(Dict.Config.TableConst.frag_equip))
                {
                    fragEquipments[data.id].num += data.num;
                }
                else if (data.id.StartsWith(Dict.Config.TableConst.frag_pet))
                {
                    fragPets[data.id].num += data.num;
                }
                else if (data.id.StartsWith(Dict.Config.TableConst.frag_trea))
                {
                    treasureFrag.AddFrag(data);
                }
                else if (data.id.StartsWith(Dict.Config.TableConst.frag_war))
                {
                    fragHeros[data.id].num += data.num;
                }
                else if (data.id.StartsWith(Dict.Config.TableConst.FishItem))
                {
                    fishItems[data.id].num += data.num;
                }
                else if (data.id.StartsWith(Dict.Config.TableConst.MineItem))
                {
                    mineItems[data.id].num += data.num;
                }
                else if (data.id == Dict.Config.TableConst.coin)
                {
                    AddCoin(data.num);
                }
                else if (data.id == Dict.Config.TableConst.diamond)
                {
                    AddDiamond(data.num);
                }
                else if (data.id == Dict.Config.TableConst.popularity)
                {
                    AddPrestige(data.num);
                }
                else if (data.id == Dict.Config.TableConst.exp)
                {
                    //AddExp(data.num);
                }
                else if (data.id == Dict.Config.TableConst.energy)
                {
                    Energy += data.num;
                }
                else if (data.id == Dict.Config.TableConst.stamina)
                {
                    Stamina += data.num;
                }
                else if (data.id == Dict.Config.TableConst.score)
                {
                    bossScore += data.num;
                }
                else if (data.id == Dict.Config.TableConst.point)
                {
                    strategyScore += data.num;
                }
                else if (data.id == Dict.Config.TableConst.light)
                {
                    retentionLight += data.num;
                }
                else if (data.id == Dict.Config.TableConst.wantedAttTimes)
                {
                    wantedLeftAttTimes += data.num;
                }
            }
        }
        public void AddEquipment(List<Equipment> equipments)
        {
            instPlayerData.AddEquipment(equipments);
        }
        public void AddTreasure(List<Treasure> treasures)
        {
            instPlayerData.AddTreasure(treasures);
        }

        public void AddHero(List<Warrior> warriors)
        {
            instPlayerData.AddHero(warriors);
        }

        public void AddPet(List<Pet> pets)
        {
            instPlayerData.AddPet(pets);
        }

        public void setFieldHpItems(string id1, string id2)
        {
            setHpItems = new Dictionary<int, string>();
            setHpItems[0] = id1;
            setHpItems[1] = id2;
        }

        #endregion
        #region 删

        public void DeleteSimpleItem(List<SimpleItem> simpleItems)
        {
            foreach (var data in simpleItems)
            {
                DeleteSimpleItem(data);
            }
        }
        public void DeleteSimpleItem(SimpleItem data)
        {
            if (data.id.StartsWith(Dict.Config.TableConst.item))
            {
                simpleGoods[data.id].num -= data.num;
            }
            else if (data.id.StartsWith(Dict.Config.TableConst.frag_equip))
            {
                fragEquipments[data.id].num -= data.num;
            }
            else if (data.id.StartsWith(Dict.Config.TableConst.frag_pet))
            {
                fragPets[data.id].num -= data.num;
            }
            else if (data.id.StartsWith(Dict.Config.TableConst.frag_trea))
            {
                treasureFrag.DeleteFrag(data);
            }
            else if (data.id.StartsWith(Dict.Config.TableConst.frag_war))
            {
                fragHeros[data.id].num -= data.num;
            }
            else if (data.id.StartsWith(Dict.Config.TableConst.FishItem))
            {
                fishItems[data.id].num -= data.num;
            }
            else if (data.id.StartsWith(Dict.Config.TableConst.MineItem))
            {
                mineItems[data.id].num -= data.num;
            }
            else if (data.id == Dict.Config.TableConst.coin)
            {
                SubCoin(data.num);
            }
            else if (data.id == Dict.Config.TableConst.diamond)
            {
                SubDiamond(data.num);
            }
            else if (data.id == Dict.Config.TableConst.popularity)
            {
                SubPrestige(data.num);
            }
            else if (data.id == Dict.Config.TableConst.energy)
            {
                Energy -= data.num;
            }
            else if (data.id == Dict.Config.TableConst.score)
            {
                bossScore -= data.num;
            }
            else if (data.id == Dict.Config.TableConst.point)
            {
                strategyScore -= data.num;
            }
            else if (data.id == Dict.Config.TableConst.light)
            {
                retentionLight -= data.num;
            }
            else if (data.id == Dict.Config.TableConst.stamina)
            {
                Stamina -= data.num;
            }
            else if (data.id == Dict.Config.TableConst.wantedAttTimes)
            {
                wantedLeftAttTimes -= data.num;
            }
        }
        public void DeleteSimpleItem(BaseResource data)
        {
            if (data.id.StartsWith(Dict.Config.TableConst.item))
            {
                simpleGoods[data.id].num -= data.num;
            }
            else if (data.id.StartsWith(Dict.Config.TableConst.frag_equip))
            {
                fragEquipments[data.id].num -= data.num;
            }
            else if (data.id.StartsWith(Dict.Config.TableConst.frag_pet))
            {
                fragPets[data.id].num -= data.num;
            }
            else if (data.id.StartsWith(Dict.Config.TableConst.frag_trea))
            {
                treasureFrag.CostFrag(data);
            }
            else if (data.id.StartsWith(Dict.Config.TableConst.frag_war))
            {
                fragHeros[data.id].num -= data.num;
            }
            else if (data.id.StartsWith(Dict.Config.TableConst.FishItem))
            {
                fishItems[data.id].num -= data.num;
            }
            else if (data.id.StartsWith(Dict.Config.TableConst.MineItem))
            {
                mineItems[data.id].num -= data.num;
            }
            else if (data.id == Dict.Config.TableConst.coin)
            {
                SubCoin(data.num);
            }
            else if (data.id == Dict.Config.TableConst.diamond)
            {
                SubDiamond(data.num);
            }
            else if (data.id == Dict.Config.TableConst.popularity)
            {
                SubPrestige(data.num);
            }
            else if (data.id == Dict.Config.TableConst.energy)
            {
                Energy -= data.num;
            }
            else if (data.id == Dict.Config.TableConst.score)
            {
                bossScore -= data.num;
            }
            else if (data.id == Dict.Config.TableConst.point)
            {
                strategyScore -= data.num;
            }
            else if (data.id == Dict.Config.TableConst.light)
            {
                retentionLight -= data.num;
            }
            else if (data.id == Dict.Config.TableConst.stamina)
            {
                Stamina -= data.num;
            }
            else if(data.id == Dict.Config.TableConst.tiredness)
            {
                Tiredness -= data.num;
            }

        }

        public void DeleteEquipment(List<string> equipments)
        {
            instPlayerData.DeleteEquipment(equipments);
        }
        public void DeleteTreasure(List<string> treasures)
        {
            instPlayerData.DeleteTreasure(treasures);
        }

        public void DeleteHero(List<string> warriors)
        {
            instPlayerData.DeleteHero(warriors);
        }

        public void DeletePet(List<string> pets)
        {
            instPlayerData.DeletePet(pets);
        }

        public void DeleteEquipment(string guid)
        {
            instPlayerData.DeleteEquipment(guid);
        }
        public void DeleteTreasure(string guid)
        {
            instPlayerData.DeleteTreasure(guid);
        }

        public void DeletePet(string guid)
        {
            instPlayerData.DeletePet(guid);
        }
        public void DeleteHero(string guid)
        {
            instPlayerData.DeleteHero(guid);
        }

        public void Delete(List<BaseResource> delete)
        {
            for (int i = 0; i < delete.Count; ++i)
            {
                Delete(delete[i]);
            }
        }

        public void Delete(BaseResource data)
        {
            if (data.id.StartsWith(Dict.Config.TableConst.war))
            {
                DeleteHero(data.guid);
            }
            else if (data.id.StartsWith(Dict.Config.TableConst.equip))
            {
                DeleteEquipment(data.guid);
            }
            else if (data.id.StartsWith(Dict.Config.TableConst.trea))
            {
                DeleteTreasure(data.guid);
            }
            else if(data.id.StartsWith(Dict.Config.TableConst.pet))
            {
                DeletePet(data.guid);
            }
            else
            {
                DeleteSimpleItem(data);
            }
        }
        #endregion
        #region 改
        public void UpdateSimpleItem(List<SimpleItem> simpleItems)
        {
            foreach (var data in simpleItems)
            {
                if (data.id.StartsWith(Dict.Config.TableConst.item))
                {
                    simpleGoods[data.id].num = data.num;
                }
                else if (data.id.StartsWith(Dict.Config.TableConst.frag_equip))
                {
                    fragEquipments[data.id].num = data.num;
                }
                else if (data.id.StartsWith(Dict.Config.TableConst.frag_pet))
                {
                    fragPets[data.id].num = data.num;
                }
                else if (data.id.StartsWith(Dict.Config.TableConst.frag_trea))
                {
                    treasureFrag.SetFrag(data);
                }
                else if (data.id.StartsWith(Dict.Config.TableConst.frag_war))
                {
                    fragHeros[data.id].num = data.num;
                }
                else if (data.id.StartsWith(Dict.Config.TableConst.FishItem))
                {
                    fishItems[data.id].num = data.num;
                }
                else if (data.id.StartsWith(Dict.Config.TableConst.MineItem))
                {
                    mineItems[data.id].num = data.num;
                }
            }
        }
        //public void UpdateEquipment(List<Equipment> equipments)
        //{
        //    instPlayerData.UpdateEquipment(equipments);
        //}
        //public void UpdateTreasure(List<Treasure> treasures)
        //{
        //    instPlayerData.UpdateTreasure(treasures);
        //}

        //public void UpdateHero(List<Warrior> warriors)
        //{
        //    instPlayerData.UpdateHero(warriors);
        //}
        public void UpdateEquipment(Equipment equipments)
        {
            instPlayerData.UpdateEquipment(equipments);
        }
        public void UpdateTreasure(Treasure treasures)
        {
            instPlayerData.UpdateTreasure(treasures);
        }

        public void UpdateHero(Warrior warriors)
        {
            instPlayerData.UpdateHero(warriors);
        }

        public void UpdatePet(Pet pet)
        {
            instPlayerData.UpdatePet(pet);
        }

        public void UpdateItemShopProducts(List<ShopItem> list)
        {
            foreach (var item in list)
            {
                UpdateItemShopProduct(item);
            }
        }

        public UIShopProduct GetShopProductByItemId(string itemId)
        {
            foreach (var sp in itemShopProductList)
            {
                foreach (var br in sp.Value.productList)
                {
                    if (br.id == itemId)
                    {
                        return sp.Value;
                    }
                }
            }
            return null;
        }

        public void UpdateItemShopProduct(ShopItem shopItem)
        {
            if (itemShopProductList.ContainsKey(shopItem.id))
            {
                itemShopProductList[shopItem.id].InitData(shopItem);
            }
            else
            {
                UIShopProduct product = new UIShopProduct();
                product.InitData(shopItem);
                itemShopProductList[product.productId] = product;
            }
        }

        public void UpdateHpSet(string itemId1,string itemId2)
        {
            setHpItems[0] = itemId1;
            setHpItems[1] = itemId2;
        }
        #endregion
    }

    public delegate void OnValueChanged();
}
